package com.jastar.android.test.demo;

import android.view.View;
import android.widget.TextView;

import com.jastar.android.test.R;
import com.jastar.android.test.abstracts.AbstractExamActivity;
import com.jastar.android.util.RandomUtil;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;

public class MathTestActivity extends AbstractExamActivity {
    private final int[] maxs = {5, 10, 20, 50};     //各级别出题上限
    private int max = 5;                            //当前出题上限

    @Override
    protected int getActivityId() {
        return R.layout.activity_math_test;
    }

    @Override
    protected QuestionItem getNextQuestionItem(int answerCount) {
        QuestionItem item = new QuestionItem();

        max = maxs[Math.min(maxs.length - 1, getLevel() - 1)];
        int num1 = random.nextInt(max) + 1;
        int num2 = random.nextInt(max) + 1;

        if (RandomUtil.judgeByPercent(1, 2)) { //加法
            item.question = format("%d + %d", num1, num2);
            item.rightAnswer = String.valueOf(num1 + num2);
            item.answers.add(item.rightAnswer);
        } else { //减法
            item.question = format("%d - %d", num1 + num2, num1);
            item.rightAnswer = String.valueOf(num2);
            item.answers.add(item.rightAnswer);
        }

        Set<Object> answerSet = new HashSet<>();
        answerSet.add(item.rightAnswer);

        IntStream.range(1, answerCount).forEach(i -> {
            String randomAnswer = randomExclude(answerSet);
            item.answers.add(randomAnswer);
            answerSet.add(randomAnswer);
        });

        Collections.shuffle(item.answers);

        return item;
    }

    @Override
    protected void setButtonByAnswer(View v, Object answer) {
        TextView text = (TextView) v;
        text.setText(String.valueOf(answer));
    }

    @Override
    protected boolean isRightAnswer(View v, Object answer) {
        TextView text = (TextView) v;
        return text.getText().equals(answer);
    }

    private String randomExclude(Set<Object> set) {
        int res = random.nextInt(max + max) + 1;
        if (!set.contains(String.valueOf(res))) {
            return String.valueOf(res);
        }
        return randomExclude(set);
    }

}